package com.example.ch02_student.adminsDo;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Looper;
import android.text.Html;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.example.ch02_student.R;
import com.example.ch02_student.entity.TeacherVo;
import com.example.ch02_student.utils.DataBean;
import com.example.ch02_student.utils.ResultTeacher;
import com.example.ch02_student.utils.ResultVo;
import com.example.ch02_student.utils.UrlBase;
import com.google.gson.Gson;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class TeacherInfo extends AppCompatActivity {
    ListView lv;
    OkHttpClient okHttpClient;
    EditText searchKey;
    List<Map<String, String>> list = null;
    private List<TeacherVo> teacherVos;
    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_teacher_info);
        okHttpClient = new OkHttpClient();
        lv = findViewById(R.id.lv);
        searchKey = findViewById(R.id.searchKey);
        //初始化页面
        init();
        int t03 = R.drawable.t03;
        System.err.println(t03);
        //单击事件
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Toast.makeText(TeacherInfo.this, "单击", Toast.LENGTH_SHORT).show();
                //获取tno
                Map<String, String> map = list.get(i);
                String tno = map.get("tno");
                Bundle bundle = new Bundle();
                bundle.putString("tno", tno);
                bundle.putString("tname", map.get("tname"));
                bundle.putString("sex", map.get("sex"));
                bundle.putString("age", map.get("age"));
                bundle.putString("tel", map.get("tel"));


                Intent intent = new Intent(TeacherInfo.this, TeacherUpdateInfo.class);
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });

        //长按事件 触发删除操作
        lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            int code;

            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
                //获取tno
                Map<String, String> map = list.get(i);
                String tno = map.get("tno");
                System.err.println(tno);
                Request build = new Request.Builder().url(UrlBase.URL_BASE + "/teacher/deleteTeacher?tno=" + tno).build();
                Call call = okHttpClient.newCall(build);

                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(@NotNull Call call, @NotNull IOException e) {
                    }

                    @Override
                    public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                        ResultVo resultVo = new Gson().fromJson(response.body().string(), ResultVo.class);
                        code = resultVo.getCode();
                        if (code == 1000) {
                            Looper.prepare();
                            Toast.makeText(TeacherInfo.this, "删除成功", Toast.LENGTH_SHORT).show();
                            init();
                            Looper.loop();
                            return;
                        } else {
                            System.err.println("error");
                        }
                    }
                });
                if (code == 1000) {
                    return true;
                } else {
                    return false;
                }

            }
        });
    }


    //初始化页面
    public void init() {
        Request build = new Request.Builder().url(UrlBase.URL_BASE + "/teacher/selectAllTeacher").build();
        Call call = okHttpClient.newCall(build);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String string = response.body().string();
                xuanran(string);
                System.err.println(list);
            }
        });
    }

    //搜索按钮
    public void search(View view) {
        String search = searchKey.getText().toString();
        Request build = new Request.Builder().url(UrlBase.URL_BASE + "/teacher/selectTeacherKey?key=" + search).build();
        Call call = okHttpClient.newCall(build);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {

            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String string = response.body().string();
                ResultTeacher resultVo1 = new Gson().fromJson(string, ResultTeacher.class);
                 teacherVos = resultVo1.getData();
                 runOnUiThread(new Runnable() {
                     @Override
                     public void run() {
                         lv.setAdapter(new MyAdapter());
                     }
                 });

                //xuanran(string);
            }
        });
    }

    //数据渲染
    public void xuanran(String string) {
        Gson gson = new Gson();
        ResultVo resultVo = gson.fromJson(string, ResultVo.class);

        List<DataBean> data = resultVo.getData();
        System.err.println(data);
        //提取教师数据（包括所教课程）
        list = new ArrayList<>();
        Map<String, String> map;
        if (data != null && data.size() > 0) {
            for (int i = 0; i < data.size(); i++) {
                DataBean teacher = data.get(i);
                map = new HashMap<>();
                map.put("tno", teacher.getTno());
                map.put("tname", teacher.getTname());

                map.put("img", teacher.getImg());
                map.put("sex", teacher.getSex());
                map.put("age", teacher.getAge().toString());
                map.put("tel", teacher.getTel());
                if (teacher.getCreateTime() != null) {
                    map.put("createTime", simpleDateFormat.format(teacher.getCreateTime()));
                }

                StringBuilder stringBuilder = new StringBuilder();
                String s = new String();
                for (int j = 0; j < teacher.getCnames().size(); j++) {
                    stringBuilder = stringBuilder.append(teacher.getCnames().get(j));
                }
                map.put("cnames", stringBuilder + "");
                list.add(map);
            }
            //key
            final String[] key = new String[]{"img", "tno", "tname", "sex", "age", "tel", "createTime", "cnames"};

            //id
            final int[] ints = new int[]{R.id.img, R.id.tno, R.id.tname, R.id.sex, R.id.age, R.id.tel, R.id.createTime, R.id.cnames};
            //回到主线程
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    SimpleAdapter simpleAdapter = new SimpleAdapter(TeacherInfo.this, list, R.layout.activity_teacher_info_items, key, ints);
                    lv.setAdapter(simpleAdapter);
                    Toast.makeText(TeacherInfo.this, "success", Toast.LENGTH_SHORT).show();


                }
            });
        } else {
            Looper.prepare();
            Toast.makeText(TeacherInfo.this, "搜索有误", Toast.LENGTH_LONG).show();
            Looper.loop();
        }

    }

    public void back(View view) {
        startActivity(new Intent(TeacherInfo.this, AdminsDo.class));
    }


    //适配器
    class MyAdapter extends BaseAdapter{

        @Override
        public int getCount() {
            return teacherVos.size();
        }

        @Override
        public Object getItem(int i) {
            return teacherVos.get(i);
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            View inflate = View.inflate(TeacherInfo.this, R.layout.activity_teacher_info_items, null);
           ImageView img =inflate.findViewById(R.id.img);
           TextView tno =inflate.findViewById(R.id.tno);
           TextView tname =inflate.findViewById(R.id.tname);
           TextView sex =inflate.findViewById(R.id.sex);
           TextView age =inflate.findViewById(R.id.age);
           TextView tel =inflate.findViewById(R.id.tel);
           TextView createTime =inflate.findViewById(R.id.createTime);
           TextView cnames =inflate.findViewById(R.id.cnames);

           if (teacherVos.size()>0){
               img.setImageResource(Integer.parseInt(teacherVos.get(i).getImg()));
               //tno
               String s = teacherVos.get(i).getTno().replaceAll("\\[", "");
               String s1 = s.replaceAll("]", "");
               tno.setText(Html.fromHtml(s1));
               //tname
               String tna = teacherVos.get(i).getTname().replaceAll("\\[", "");
               String tna1 = tna.replaceAll("]", "");
               tname.setText(Html.fromHtml(tna1));
                //sex
               String se = teacherVos.get(i).getSex().replaceAll("\\[", "");
               String se1 = se.replaceAll("]", "");
               sex.setText(Html.fromHtml(se1));
               //tel
               String te = teacherVos.get(i).getTel().replaceAll("\\[", "");
               String te1 = te.replaceAll("]", "");
               tel.setText(Html.fromHtml(te1));

               //cnames
               if (teacherVos.get(i).getCnames().size()>0){
                   String cn = teacherVos.get(i).getCnames().get(0).replaceAll("\\[", "");
                   String cn1 = cn.replaceAll("]", "");
                   cnames.setText(Html.fromHtml(cn1));
               }else {
                   cnames.setText(Html.fromHtml(""));
               }


               age.setText(teacherVos.get(i).getAge()+"");
               createTime.setText(simpleDateFormat.format(teacherVos.get(i).getCreateTime()));



           }

           return inflate;



        }
    }

}
